package com.yupi.springbootinit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.mapper.ChapterMapper;
import com.yupi.springbootinit.model.entity.Chapter;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.model.entity.UserCourse;
import com.yupi.springbootinit.model.vo.ChapterVO;
import com.yupi.springbootinit.service.ChapterService;
import com.yupi.springbootinit.service.UserCourseService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {
    
    @Resource
    private UserCourseService userCourseService;

    @Override
    public ChapterVO getChapterDetail(long courseId, long chapterId, User loginUser) {
        // 获取章节信息
        QueryWrapper<Chapter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id", courseId);
        queryWrapper.eq("sort", chapterId);
        Chapter chapter = this.getOne(queryWrapper);
        if (chapter == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "章节不存在");
        }
        
        ChapterVO chapterVO = new ChapterVO();
        BeanUtils.copyProperties(chapter, chapterVO);
        
        // 如果用户未登录
        if (loginUser == null) {
            chapterVO.setContent(null);
            chapterVO.setCanAccess(false);
            return chapterVO;
        }
        
        // 检查是否已报名
        QueryWrapper<UserCourse> enrollQueryWrapper = new QueryWrapper<>();
        enrollQueryWrapper.eq("user_id", loginUser.getId());
        enrollQueryWrapper.eq("course_id", courseId);
        enrollQueryWrapper.eq("type", 1);
        boolean hasEnrolled = userCourseService.count(enrollQueryWrapper) > 0;
        
        // 设置是否可访问
        chapterVO.setCanAccess(hasEnrolled);
        
        // 未报名用户看不到具体内容
        if (!hasEnrolled) {
            chapterVO.setContent(null);
        }
        // 已报名用户可以看到内容，不需要清空 content
        
        return chapterVO;
    }
} 